const os = require('os');

/**
 * 获取本机网络IP地址
 * 自动检测当前网络环境，返回最适合的IP地址
 */
function getNetworkIP() {
  // 首先尝试从环境变量获取指定的IP
  const envIP = process.env.NETWORK_IP;
  if (envIP) {
    console.log(`🌐 使用环境变量指定的IP: ${envIP}`);
    return envIP;
  }
  
  const interfaces = os.networkInterfaces();
  const ips = [];
  
  console.log('🔍 开始检测网络接口...');
  
  // 遍历所有网络接口
  Object.keys(interfaces).forEach(name => {
    const iface = interfaces[name];
    console.log(`📡 检查接口: ${name}`);
    
    iface.forEach(addr => {
      console.log(`  - ${addr.family}: ${addr.address} (内部: ${addr.internal})`);
      
      // 只获取IPv4地址，排除内部地址
      if (addr.family === 'IPv4' && !addr.internal) {
        ips.push({
          interface: name,
          ip: addr.address,
          netmask: addr.netmask,
          mac: addr.mac
        });
        console.log(`    ✅ 添加到候选列表: ${addr.address}`);
      }
    });
  });
  
  console.log(`📋 检测到 ${ips.length} 个外部IPv4地址`);
  
  // 优先选择常见的局域网网段
  const preferredRanges = [
    '192.168.',    // 家庭/办公室网络
    '10.',         // 企业网络
    '172.16.',     // 企业网络
    '172.17.',
    '172.18.',
    '172.19.',
    '172.20.',
    '172.21.',
    '172.22.',
    '172.23.',
    '172.24.',
    '172.25.',
    '172.26.',
    '172.27.',
    '172.28.',
    '172.29.',
    '172.30.',
    '172.31.'
  ];
  
  // 按优先级排序
  ips.sort((a, b) => {
    // 优先选择WLAN接口
    const aIsWLAN = a.interface.toLowerCase().includes('wlan') || a.interface.toLowerCase().includes('wireless');
    const bIsWLAN = b.interface.toLowerCase().includes('wlan') || b.interface.toLowerCase().includes('wireless');
    
    if (aIsWLAN && !bIsWLAN) return -1;
    if (!aIsWLAN && bIsWLAN) return 1;
    
    // 排除VMware虚拟网卡
    const aIsVMware = a.interface.toLowerCase().includes('vmware') || a.interface.toLowerCase().includes('vmnet');
    const bIsVMware = b.interface.toLowerCase().includes('vmware') || b.interface.toLowerCase().includes('vmnet');
    
    if (!aIsVMware && bIsVMware) return -1;
    if (aIsVMware && !bIsVMware) return 1;
    
    const aIndex = preferredRanges.findIndex(range => a.ip.startsWith(range));
    const bIndex = preferredRanges.findIndex(range => b.ip.startsWith(range));
    
    // 如果都在优先范围内，按索引排序
    if (aIndex !== -1 && bIndex !== -1) {
      return aIndex - bIndex;
    }
    
    // 优先范围内的排在前面
    if (aIndex !== -1) return -1;
    if (bIndex !== -1) return 1;
    
    // 都不在优先范围内，按IP地址排序
    return a.ip.localeCompare(b.ip);
  });
  
  const selectedIP = ips.length > 0 ? ips[0].ip : '127.0.0.1';
  console.log(`🎯 最终选择的IP: ${selectedIP}`);
  
  return selectedIP;
}

/**
 * 获取完整的网络URL
 * @param {string} port - 端口号
 * @param {string} path - 路径
 * @returns {string} 完整的URL
 */
function getNetworkURL(port = '3000', path = '') {
  const ip = getNetworkIP();
  const url = `http://${ip}:${port}${path}`;
  
  console.log(`🌐 自动获取网络IP: ${ip}`);
  console.log(`🔗 生成网络URL: ${url}`);
  
  return url;
}

/**
 * 处理图片URL，自动替换为网络IP
 * @param {string} imagePath - 图片路径
 * @param {string} port - 端口号
 * @returns {string} 处理后的完整URL
 */
function processImageURL(imagePath, port = '3000') {
  if (!imagePath) return '';
  
  // 如果已经是完整URL，检查是否需要替换localhost
  if (imagePath.startsWith('http')) {
    if (imagePath.includes('localhost') || imagePath.includes('127.0.0.1')) {
      const path = imagePath.replace(/^https?:\/\/[^\/]+/, '');
      return getNetworkURL(port, path);
    }
    return imagePath;
  }
  
  // 相对路径，拼接网络URL
  const fullPath = imagePath.startsWith('/') ? imagePath : `/${imagePath}`;
  return getNetworkURL(port, fullPath);
}

module.exports = {
  getNetworkIP,
  getNetworkURL,
  processImageURL
};
